package com.hue.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*
    自定义的gateway过滤器
 */
@Component
@Slf4j
public class MyFilter implements Ordered, GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("come in gatewayFilter...");
        String username = exchange.getRequest().getQueryParams().getFirst("username");
        if(username==null || username.equals("")){
            log.info("用户名不能为空");
            //设置响应状态码
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            //拒绝访问
            return exchange.getResponse().setComplete();
        }
        //放行
        return chain.filter(exchange);
    }

    //加载的优先级，越小加载的优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
